package mymac.com.weather;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by mymac on 2017/3/3.
 */

public class HttpRequest {
    public static HttpRequest request = null;

    public static HttpRequest getInstance(){
        if (request == null){
            request = new HttpRequest();
        }
        return request;
    }

    public void getRequest(final String address, final Handler handler){
        final Message msg = Message.obtain();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(address);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200){
                        InputStream in = conn.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        StringBuffer sb = new StringBuffer();
                        String rl = null;
                        while ((rl = br.readLine()) != null){
                            sb.append(rl);
                        }
                        String result = sb.toString();
                        JSONObject json = new JSONObject(result);
                        msg.obj = json;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
